package recycle.controller;

import io.vertx.core.MultiMap;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import recycle.common.ResponseHandler;
import recycle.pojo.Category;
import recycle.service.CategoryService;

public class CategoryController {
    private final CategoryService categoryService;

    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    public void setupRoutes(Router router) {

        router.post("/categories/create").handler(this::create);
        router.delete("/categories/delete/:id").handler(this::delete);
        router.put("/categories/update").handler(this::update);
        router.get("/categories/details/:id").handler(this::details);
        router.post("/categories/list").handler(this::list);
        router.post("/categories/listAll").handler(this::listAll);
    }



    private void create(RoutingContext ctx) {
        Category category = ctx.body().asPojo(Category.class);
        categoryService.create(category).onComplete(ResponseHandler.handle(ctx));
    }

    private void list(RoutingContext ctx) {
        Category category = ctx.body().asPojo(Category.class);
        MultiMap params = ctx.request().params();
        Integer pageNum = params.get("pageNum") != null ? Integer.parseInt(params.get("pageNum")) : 1;
        Integer pageSize = params.get("pageSize")!= null ? Integer.parseInt(params.get("pageSize")) : 10;
        categoryService.list(category,pageNum,pageSize).onComplete(ResponseHandler.handle(ctx));
    }

    private void listAll(RoutingContext ctx) {
        categoryService.list().onComplete(ResponseHandler.handle(ctx));
    }

    private void details(RoutingContext ctx) {
        Long id = Long.parseLong(ctx.pathParam("id"));
        categoryService.details(id).onComplete(ResponseHandler.handle(ctx));
    }


    private void update(RoutingContext ctx) {
        Category category = ctx.body().asPojo(Category.class);
        categoryService.update(category).onComplete(ResponseHandler.handle(ctx));
    }

    private void delete(RoutingContext ctx) {
        Long id = Long.parseLong(ctx.pathParam("id"));
        categoryService.delete(id).onComplete(ResponseHandler.handle(ctx));
    }
}